// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

use std::collections::HashMap;
use std::path::Path;

use sysinfo::Disks;
use tauri::Error;
use tauri_plugin_log::{Target, TargetKind};

use crate::filefind::{FileInfo, find_large_files, find_repeat_files};

mod filefind;

// Learn more about Tauri commands at https://tauri.app/v1/guides/features/command
#[tauri::command]
fn greet(name: &str) -> String {
    format!("Hello, {}! You've been greeted from Rust!", name)
}

#[tauri::command]
async fn list_dir_by_path(path: String) -> Result<Vec<FileInfo>, Error> {
    let vec = filefind::visit_dir_first(Path::new(&path));
    Ok(vec)
}

#[tauri::command]
async fn del_files(paths: Vec<String>) -> Result<(), Error> {
    let _ = filefind::del_files(paths);
    Ok(())
}

#[tauri::command]
async fn copy_files(paths: Vec<String>, dest: String) -> Result<(), Error> {
    if let Err(e) = filefind::copy_file(paths, dest, false) {
        return Err(Error::Io(e));
    }
    Ok(())
}

#[tauri::command]
async fn disks_info() -> Result<Vec<HashMap<String, String>>, Error> {
    let mut vec = Vec::new();
    let disks = Disks::new_with_refreshed_list();
    for disk in disks.list() {
        let mut map = HashMap::new();
        map.insert("name".to_string(), disk.name().to_str().unwrap().to_string());
        map.insert("mount".to_string(), disk.mount_point().to_str().unwrap().to_string());
        vec.push(map);
    }
    Ok(vec)
}

#[tauri::command]
async fn find_large_file(paths: Vec<String>) -> Result<Vec<FileInfo>, Error> {
    let vec = find_large_files(paths);
    Ok(vec)
}

#[tauri::command]
async fn find_repeat_file(paths: Vec<String>) -> Result<HashMap<String, Vec<FileInfo>>, Error> {
    let vec = find_repeat_files(paths);
    Ok(vec)
}

fn main() {
    tauri::Builder::default()
        .plugin(tauri_plugin_log::Builder::new()
            .targets([
                Target::new(TargetKind::Stdout),
                // Target::new(TargetKind::LogDir { file_name: Some("D:\\tmp\\log\\taurifirst.log".to_string()) }),
                Target::new(TargetKind::Webview),
            ]).build())
        .plugin(tauri_plugin_fs::init())
        .plugin(tauri_plugin_shell::init())
        .invoke_handler(tauri::generate_handler![greet,
            find_large_file,disks_info,
            find_repeat_file,del_files,copy_files,
            list_dir_by_path])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
